<?php

namespace app\common\service;

use app\bbs\model\BbsArticle;
use app\bbs\model\BbsArticleLabel;
use app\common\enum\transaction\SourceTypeEnum;
use app\common\enum\transaction\TypeEnum;
use app\common\model\Article;
use app\user\model\UserShare;
use app\http\exception\ApiException;
use randy\tools\units\ExtendQueryHelper;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class UserShareService extends BaseService
{
    public function getUserShareList(ExtendQueryHelper $extendQueryHelper, $data)
    {
        $query = UserShare::build()
                          ->where($extendQueryHelper->where)
                          ->order($extendQueryHelper->sort, $extendQueryHelper->order);
        $list = $extendQueryHelper->is_page ? $query->_paginate() : $query->select();
        return $list;
    }

    public function getUserShareItem($id)
    {
        return UserShare::build()
            ->findOrFail($id);
    }

    public function delUserShareItem($id)
    {
        $info = UserShare::find($id);
        return $info->delete();
    }

    public function setUserShareItem($id, $data)
    {
        $info = UserShare::find($id);
        $info->save($data);
        return $info;
    }


    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function addUserShareItem($data ,$user_id)
    {
        $model = new UserShare();
        return $model->transaction(function () use ($user_id, $model, $data)
        {
            $data['user_share_uuid'] = uuid();
            $data['create_date'] = date('Y-m-d');
            $model->save($data);
            if ($data['share_type'] == 1) {
                BbsArticle::build()
                          ->where('article_id', $data['article_id'])
                          ->setInc('share_num');
            }
            // 发放积分
            $point = get_setting('每分享一次可获得积分数');
            UserMoneyService::changeUserPoint($point, $user_id, TypeEnum::SR->value, $data['user_share_uuid'], SourceTypeEnum::FX->value, '分享', '分享资讯积分奖励', $data['article_id'] ?? 0);
            return $model;
        });
    }


}
